//
//  TSMyTeamViewController.swift
//  TSProfitProject
//
//  Created by TmmmS on 2019/11/22.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import MJRefresh

class TSMyTeamViewController: TSBaseViewController {
    
    var tableController : TSBaseTableViewController!
    lazy var agentArray = Array<TSMyteamModel>()
    lazy var agentLevelArray = Array<TSTeamAgentLevelModel>()
    
    lazy var infoHeader : TSTeamInfoHeaderView = {
        var header = TSTeamInfoHeaderView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 60))
        return header
    }()
    
    lazy var agentHeader : TSTeamAgentHeaderView = {
        var header = TSTeamAgentHeaderView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 60))
        return header
    }()
    
    lazy var branchHeader : TSTeamBranchHeaderView = {
        var header = TSTeamBranchHeaderView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 60))
        return header
    }()

    @objc func refreshDatas() {
        requestAgentDatas()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configViews()
        setupNavigationTitle(title: "我的团队")
        requestAgentDatas()
    }

}

extension TSMyTeamViewController : UITableViewDelegate {

//    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        35
//    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        60
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 0:
            return infoHeader
        case 1:
            return agentHeader
        case 2:
            return branchHeader
        default:
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0.001))
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        0.001
    }
}

extension TSMyTeamViewController : UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        switch section {
        case 0:
            return 1
        case 1:
            return agentLevelArray.count
        case 2:
            return agentArray.count
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell : UITableViewCell!
        
        if indexPath.section == 1 || indexPath.section == 2 {
            
            var agentCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSTeamAgentTableViewCell.self)) as? TSTeamAgentTableViewCell
            
            if agentCell == nil {
                agentCell = TSTeamAgentTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSTeamAgentTableViewCell.self))
            }
            
            if indexPath.section == 1 {
                agentCell?.setupCell(model: agentLevelArray[indexPath.row])
            } else {
                agentCell?.setupCell(model: agentArray[indexPath.row])
            }
            
            cell = agentCell
            
        } else {
            
            var normalCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSTeamNormalTableViewCell.self)) as? TSTeamNormalTableViewCell
            
            if normalCell == nil {
                normalCell = TSTeamNormalTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSTeamNormalTableViewCell.self))
            }
            
            normalCell?.setupCell(name: TSLoginManager.shared._usermodel!.username!, userId: "\(TSLoginManager.shared._usermodel!.user_id)", level: TSLoginManager.shared._usermodel!.dengji, trade: String.init(format: "%.2f", TSLoginManager.shared._usermodel!.liushui), people: TSLoginManager.shared._usermodel!.item_num)

            cell = normalCell
        }
        
        return cell
    
    }
}

extension TSMyTeamViewController {
    
    func requestAgentDatas() {
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.getMyteam, showHUD: true, success: { (data) in
            
            self.agentArray.removeAll()
            
            let array = data as? Array<Dictionary<String, Any>>
            if array?.count ?? 0 > 0 {
                for item in array! {
                    let tempModel = TSMyteamModel.deserialize(from: item)
                    if let model = tempModel {
                        self.agentArray.append(model)
                    }
                }
            }
            self.tableController.tableView.reloadData()
            
            self.requestAgentLevelDatas()
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    func requestAgentLevelDatas() {
        
        TSNetworkManager.request(TMSNetworkTools.getAgentLevel, showHUD: true, success: { (data) in
            CBToast.hiddenToastAction()
            
            let array = data as? Array<Dictionary<String, Any>>
            if array?.count ?? 0 > 0 {
                for item in array! {
                    let tempModel = TSTeamAgentLevelModel.deserialize(from: item)
                    if let model = tempModel {
                        self.agentLevelArray.append(model)
                    }
                }
            }
            self.tableController.tableView.reloadData()
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
}

extension TSMyTeamViewController {
    
    func configViews() {
        
        tableController = TSBaseTableViewController(style: .grouped)
        tableController.shouldDisplayEmptyAlert = false
        tableController.tableView.backgroundColor = WHITE_COLOR
        tableController.tableView.delegate = self;
        tableController.tableView.dataSource = self
        tableController.tableView.separatorStyle = .none
        tableController.tableView.estimatedRowHeight = 100
        tableController.tableView.rowHeight = UITableView.automaticDimension
        self.view.addSubview(tableController.tableView)
        tableController.tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(T_NAVBARHEIGHT)
        }
        
        tableController.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshDatas))
    }
}
